package com.edais.actions;

import java.io.Serializable;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.Bank;
import com.edais.domain.Finance;
import com.edais.domain.IpLogBean;
import com.edais.domain.OrderFormRecharge;
import com.edais.domain.User;
import com.edais.domain.zftPay.FastPayTokenParamters;
import com.edais.domain.zftPay.PayParamtersTemp;
import com.edais.domain.zftPay.RechargeTokenParamters;
import com.edais.log.IpLog;
import com.edais.service.CenterService;
import com.edais.service.PayService;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import com.edais.util.StrUtil;
import com.edais.util.ThirdPartyEnvUtil;
import com.edais.util.RSAThirdParty.RSA;

@Controller
@RequestMapping("/zftPay")

public class PayAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(PayAction.class);

	@Autowired
	private CenterService centerService;

	@Autowired
	private UserService userService;

	@Autowired
	private PayService payService;


	/**
	 * 支付通快捷支付_预下单
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/zftFastPayToken")
	public void zftFastPayToken(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		// // 交易金额(元)
		// String txAmt = paramsMap.get("buyAmount");
		// // 手机号
		// String mobileNo = paramsMap.get("mobileNo");
		// // 购买的理财计划id
		// String financeId = paramsMap.get("financeID");
		// // 绑定银行卡id
		// String backCardId = paramsMap.get("backCardId");
		// // 是否使用余额购买(Y/N)
		// String isUseBalance = paramsMap.get("isUseBalance");
		// // 资金流转方式
		// String cycleMatchType = paramsMap.get("cycleMatchType");
		// // 邀请码(可为空)
		// String invitationCd = paramsMap.get("invitationCd");

		// ip记录
		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("银行卡购买");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"在APP端进行了银行卡购买操作【支付通】");

		try {
			// 参数检查
			Map<String, String> checkRes = payService
					.fastPayTokenCheckData(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("支付通快捷支付_预下单数据检查失败" + checkRes.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}

			// 主业务处理
			paramsMap.put("txAmt", checkRes.get("sum"));// 购买金额（分）
			paramsMap.put("sum_yuan", checkRes.get("sum_yuan"));// 购买金额（元）
			Map<String, String> resMap = payService
					.dealZftFastPayToken(paramsMap);
			
			if (!Consts.SUCCESS_CODE.equals(resMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.CHECK_CODE, "", resMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			jsonMap.put("orderId", resMap.get("orderId"));

			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("zftPay/zftFastPayToken 异常:" + e.getMessage());
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 支付通支付
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/zftFastPay")
	public void zftFastPay(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		// 流水号
		String orderId = paramsMap.get("orderId");
		// 手机验证码
		// String phoneToken = paramsMap.get("phoneToken");

		// ip记录
		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("银行卡购买");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"在APP端进行了银行卡购买操作【支付通】");

		try {
			Map<String, String> payResult = doZftFastPay(paramsMap);
			//系统异常的情况下直接退出
			if (!"TRADE_SUCCESS".equals(payResult.get("code")) &&
					!"TRADE_FAIL".equals(payResult.get("code"))) {
				logger.error("支付通快捷支付_下单失败" + payResult.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE,
						"", payResult.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}

			String responseMsg = payResult.get("responseMsg");

			/** 查询充值订单表ORDER_FORM_RECHARGE中对应的数据 */
			OrderFormRecharge rechargeOrderFormRtn = centerService
					.selectOrderFromRechargeByOrderId(orderId);
			// 订单状态
			String rechargeStatus = rechargeOrderFormRtn
					.getRecharge_orderform_status();
			// 订单金额
			String sum = rechargeOrderFormRtn.getAmount() + "";

			Map<String, Object> mapParam = new HashMap<String, Object>();
			mapParam.put("no_order", orderId);
			mapParam.put("info_order", "");
			mapParam.put("oid_paybill", "");
			mapParam.put("reqStr", responseMsg);
			mapParam.put("rechargeStatus", rechargeStatus);
			mapParam.put("status",payResult.get("code"));

			// 1:更新充值订单表
			if (centerService.updOrderFormRechargeInit(mapParam) == false) {
				logBean.setStatus(Consts.SUCCESS_CN);
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 充值失败直接退出
			if(!"TRADE_SUCCESS".equals(payResult.get("code"))){
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.ERROR_CODE, "", payResult.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 2. 调用核心接口充值
			mapParam.put("userId", userId);
			mapParam.put("sum", sum);
			mapParam.put("orderId", orderId);
			Map resmap = centerService.recharge(mapParam);
			if (resmap == null || !"00000".equals(resmap.get("rescode"))) {
				logger.error("支付通 充值_快捷支付_下单处理中充值异常" + resmap.get("resmsg"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 3.使用邀请码
			User user = userService.getUserDetail(userId);
			String planId = payResult.get("planId");
			String cycleMatchType = payResult.get("cycleMatchType");
			String invitationCode = payResult.get("invitationCode");
			String buyAmount = payResult.get("buyAmount");

			Finance finance = centerService.getFinanceplanDetail(planId, "");

			// 初始化订单个数
//			String buyOrderId = "";

			// 邀请码
			if ("Y".equals(finance.getIf_support_invicode())
					&& !StringUtils.isBlank(invitationCode)
					&& !invitationCode.equalsIgnoreCase(user
							.getInvitation_code())) {
				/**
				 * 1:输入邀请码的情况下，先判断此邀请码是否存在且非本人 2:如果有效且非本人，则判断被邀请人是否是首次加入“e计划”，
				 */
				int count = userService.getUserNotMeByInviteCode(
						invitationCode.toUpperCase(), userId);
				if (count > 0) {
					mapParam.put("invitationCode", invitationCode.toUpperCase());
				}
			}

			
			// 4.购买鼓钱包E300006
			mapParam.put("buyAmount", buyAmount);
			mapParam.put("planId", planId);
			mapParam.put("cycleMatchType", cycleMatchType);
			resmap = centerService.buyPlan(mapParam);
			if (resmap == null || !"00000".equals(resmap.get("rescode"))) {
				logger.error("支付通 充值_快捷支付_下单处理中购买产品异常" + resmap.get("resmsg"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} 
//			else {
//				// 获取鼓钱包订单号
//				buyOrderId = resmap.get("orderId") + "";
//			}
			
			logBean.setStatus(Consts.SUCCESS_CN);
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("zftPay/zftFastPay 异常:" + e.getMessage());
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 支付通快捷支付短信验证码重发
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/fastPayReSend")
	public void fastPayReSend(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 流水号
		String orderId = paramsMap.get("orderId");

		try {
			if (StringUtils.isBlank(orderId)) {
				logger.error("zftPay/fastPayReSend 参数异常");
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			paramsMap.put("platform_en_name", "ZHIFUTONGPAY");
			Map<String, String> dealRes = payService
					.dealFastPayReSend(paramsMap);
			
			if (!Consts.SUCCESS_CODE.equals(dealRes.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.CHECK_CODE, "", dealRes.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("zftPay/fastPayReSend 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 根据选择的银行卡选择对应的支付平台
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPayPlatformById")
	public void getPayPlatformById(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 选择的银行id
		String bankId = paramsMap.get("bankId");
		
		if(StringUtils.isBlank(bankId)){
			logger.error("zftPay/getPayPlatformById 参数异常");
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try{
			Bank bank = payService.getPayPlatformById(paramsMap);
			jsonMap.put("platform_en_name", bank.getPlatform_en_name());
			
			String result = CommonUtil.setResultStringCn(
					jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.error("zftPay/fastPayReSend 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	// 支付通下单处理
	private Map<String, String> doZftFastPay(Map<String, String> map)
			throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();

		// 获取购买参数
		String platform = "ZHIFUTONGPAY";
		map.put("platform_en_name", platform);
		PayParamtersTemp payParamtersTemp = payService.getPayParameter(map);
		if (payParamtersTemp == null) {
			logger.error("支付通快捷支付_下单获取购买参数失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		FastPayTokenParamters fastPayParamters = (FastPayTokenParamters) JsonUtil
				.getObjectFromJsonString(payParamtersTemp.getParameter_str(),
						FastPayTokenParamters.class);
		
		// 请求参数封装
		Map<String, String> payParamMap = new HashMap<String, String>();
		payParamMap.put("tradeOrderId", map.get("orderId"));// 流水号
		payParamMap.put("trDt", fastPayParamters.getTrDt());// 交易时间
		payParamMap.put("phoneToken", map.get("phoneToken"));// 手机验证码
		payParamMap.put("fastPayToken", fastPayParamters.getFastPayToken());// 平台验证码

//		String param = CommonUtil.getHttpParameterFromMap(payParamMap);
//		logger.debug("支付通快捷支付下单请求参数："+param);
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(payParamMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("fastPayUrl");

		String fastPayResult = CommonUtil.sendPostByHttp(url, requestParam);
		
		if( null == fastPayResult ){
			logger.error("支付通快捷支付下单失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message","支付下单失败");
			return resMap;
		}else{
			//解析发送结果
			Map payResultMap = JsonUtil.getMapFromJsonString(fastPayResult);
			if(null == payResultMap  || "sysException".equals(payResultMap.get("rescode"))){
				// 系统异常
				logger.error("支付通快捷支付预下单失败:" + String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "支付下单失败");
				return resMap;
			}else if("BusinessException".equals(payResultMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("支付通快捷支付下单失败:" + String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("code", "TRADE_FAIL");
				resMap.put("message", String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("responseMsg", String.valueOf(payResultMap.get("responseMsg")));
				return resMap;
			}else{
				resMap.put("code", "TRADE_SUCCESS");
				resMap.put("message", Consts.SUCCESS_DESCRIBE);
				resMap.put("responseMsg", String.valueOf(payResultMap.get("responseMsg")));
				resMap.put("planId", fastPayParamters.getPlanId());
				resMap.put("cycleMatchType", fastPayParamters.getCycleMatchType());
				resMap.put("invitationCode", fastPayParamters.getInvitationCode());
				resMap.put("buyAmount", fastPayParamters.getBuyAmount());
				return resMap;
			}
		}
	}
	
	
	/**
	 * 支付通快捷支付_预下单(仅充值)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/zftRechargeToken")
	public void zftRechargeToken(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		// 充值金额(元)
		String rechargeAmount = paramsMap.get("rechargeAmount");
		// 绑定银行卡id
		String backCardId = paramsMap.get("backCardId");
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

		// ip记录
		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("银行卡充值");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);

		if("2".equals(setupFlag)){
			logBean.setDetail(userId+"在APP端进行了充值操作【支付通】");
		}else{
			logBean.setDetail(userId+"在WEB端进行了充值操作【支付通】");
		}

		try {
			// 参数检查
			Map<String, String> checkRes = payService
					.rechargeTokenCheckData(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("支付通充值_预下单检查失败" + checkRes.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}

			// 主业务处理
			paramsMap.put("amount_fen", checkRes.get("amount_fen"));// 充值金额（分）
			Map<String, String> resMap = payService
					.dealRechargeToken(paramsMap);
			
			if (!Consts.SUCCESS_CODE.equals(resMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.CHECK_CODE, "", resMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			jsonMap.put("orderId", resMap.get("orderId"));

			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("zftPay/zftRechargeToken 异常:" + e.getMessage());
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 支付通支付(仅充值)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/zftRecharge")
	public void zftRecharge(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		// 流水号
		String orderId = paramsMap.get("orderId");
		// 手机验证码
		 String phoneToken = paramsMap.get("phoneToken");
		 String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

		// ip记录
		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("银行卡充值");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);

		if("2".equals(setupFlag)){
			logBean.setDetail(userId+"在APP端进行了充值操作【支付通】");
		}else{
			logBean.setDetail(userId+"在WEB端进行了充值操作【支付通】");
		}

		try {
			if(StringUtils.isBlank(phoneToken)){
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String,Object>(),
						Consts.CHECK_CODE, "", Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			if(StringUtils.isBlank(userId) || StringUtils.isBlank(orderId)){
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String,Object>(),
						Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 发送标识
			if(StrUtil.setupFlagCheck(setupFlag) == false){
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(new HashMap<String,Object>(),
						Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 充值处理
			Map<String, String> payResult = doZftRecharge(paramsMap);
			//系统异常的情况下直接退出
			if (!"TRADE_SUCCESS".equals(payResult.get("code")) &&
					!"TRADE_FAIL".equals(payResult.get("code"))) {
				logger.error("支付通充值_下单失败" + payResult.get("message"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE,
						"", payResult.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}

			String responseMsg = payResult.get("responseMsg");

			/** 查询充值订单表ORDER_FORM_RECHARGE中对应的数据 */
			OrderFormRecharge rechargeOrderFormRtn = centerService
					.selectOrderFromRechargeByOrderId(orderId);
			// 订单状态
			String rechargeStatus = rechargeOrderFormRtn
					.getRecharge_orderform_status();
			// 订单金额
			String sum = rechargeOrderFormRtn.getAmount() + "";

			Map<String, Object> mapParam = new HashMap<String, Object>();
			mapParam.put("no_order", orderId);
			mapParam.put("info_order", "");
			mapParam.put("oid_paybill", "");
			mapParam.put("reqStr", responseMsg);
			mapParam.put("rechargeStatus", rechargeStatus);
			mapParam.put("status",payResult.get("code"));

			// 1:更新充值订单表
			if (centerService.updOrderFormRechargeInit(mapParam) == false) {
				logBean.setStatus(Consts.SUCCESS_CN);
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 充值失败直接退出
			if(!"TRADE_SUCCESS".equals(payResult.get("code"))){
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(jsonMap,
						Consts.ERROR_CODE, "", payResult.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 2. 调用核心接口充值
			mapParam.put("userId", userId);
			mapParam.put("sum", sum);
			mapParam.put("orderId", orderId);
			Map resmap = centerService.recharge(mapParam);
			if (resmap == null || !"00000".equals(resmap.get("rescode"))) {
				logger.error("支付通充值下单异常" + resmap.get("resmsg"));
				if (StringUtils.isNotBlank(ip)) {
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			logBean.setStatus(Consts.SUCCESS_CN);
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(jsonMap,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("zftPay/zftRecharge 异常:" + e.getMessage());
			if (StringUtils.isNotBlank(ip)) {
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					"",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	// 支付通下单处理（仅充值）
	private Map<String, String> doZftRecharge(Map<String, String> map)
			throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();

		// 获取充值临时参数
		String platform = "ZHIFUTONGPAY";
		map.put("platform_en_name", platform);
		PayParamtersTemp payParamtersTemp = payService.getPayParameter(map);
		if (payParamtersTemp == null) {
			logger.error("支付通充值下单获取充值临时参数失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		RechargeTokenParamters rechargeTokenParamters = (RechargeTokenParamters) JsonUtil
				.getObjectFromJsonString(payParamtersTemp.getParameter_str(),
						RechargeTokenParamters.class);
		
		// 请求参数封装
		Map<String, String> payParamMap = new HashMap<String, String>();
		payParamMap.put("tradeOrderId", map.get("orderId"));// 流水号
		payParamMap.put("trDt", rechargeTokenParamters.getTrDt());// 交易时间
		payParamMap.put("phoneToken", map.get("phoneToken"));// 手机验证码
		payParamMap.put("fastPayToken", rechargeTokenParamters.getFastPayToken());// 平台验证码
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(payParamMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("fastPayUrl");

		String fastPayResult = CommonUtil.sendPostByHttp(url, requestParam);
		
		if( null == fastPayResult ){
			logger.error("支付通充值下单失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message","支付通充值下单失败");
			return resMap;
		}else{
			//解析发送结果
			Map payResultMap = JsonUtil.getMapFromJsonString(fastPayResult);
			if(null == payResultMap  || "sysException".equals(payResultMap.get("rescode"))){
				// 系统异常
				logger.error("支付通充值下单失败:" + String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "充值下单失败");
				return resMap;
			}else if("BusinessException".equals(payResultMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("支付通充值下单失败:" + String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("code", "TRADE_FAIL");
				resMap.put("message", String.valueOf(payResultMap.get("resmsg_cn")));
				resMap.put("responseMsg", String.valueOf(payResultMap.get("responseMsg")));
				return resMap;
			}else{
				resMap.put("code", "TRADE_SUCCESS");
				resMap.put("message", Consts.SUCCESS_DESCRIBE);
				resMap.put("responseMsg", String.valueOf(payResultMap.get("responseMsg")));
				return resMap;
			}
		}
	}

}
